<template>
  <div class="auth-container">
    <div class="auth-card" style="width: 700px; padding: 30px;">
      <h2 class="register-title">用户注册</h2>
      
      <el-steps :active="activeStep" align-center>
        <el-step title="角色选择" />
        <el-step title="基本信息" />
        <el-step title="钱包连接" />
      </el-steps>
      
      <!-- 第一步：角色选择 -->
      <div v-if="activeStep === 1" class="step-content">
        <div class="role-selection">
          <h3>请选择您的角色</h3>
          <div class="role-cards">
            <el-card 
              class="role-card" 
              :class="{ 'selected': selectedRole === 'patient' }"
              @click="selectRole('patient')"
            >
              <div class="role-icon">
                <el-icon><User /></el-icon>
              </div>
              <h4>患者</h4>
              <p>注册为患者用户，管理个人病历信息</p>
            </el-card>
            
            <el-card 
              class="role-card" 
              :class="{ 'selected': selectedRole === 'doctor' }"
              @click="selectRole('doctor')"
            >
              <div class="role-icon">
                <el-icon><FirstAidKit /></el-icon>
              </div>
              <h4>医生</h4>
              <p>注册为医生用户，管理患者病历信息</p>
            </el-card>
            
            <el-card 
              class="role-card" 
              :class="{ 'selected': selectedRole === 'admin' }"
              @click="selectRole('admin')"
            >
              <div class="role-icon">
                <el-icon><Setting /></el-icon>
              </div>
              <h4>医院管理员</h4>
              <p>注册为管理员，管理系统用户和医院信息</p>
            </el-card>
          </div>
          
          <div class="action-buttons">
            <el-button 
              type="primary" 
              class="next-btn"
              :disabled="!selectedRole"
              @click="nextStep"
            >
              下一步
            </el-button>
          </div>
          
          <div class="link-text">
            <span>已有账号？</span>
            <el-link type="primary" @click="returnToLogin">返回登录</el-link>
          </div>
        </div>
      </div>
      
      <!-- 第二步：基本信息 -->
      <div v-if="activeStep === 2" class="step-content">
        <el-form 
          :model="basicForm" 
          label-width="100px" 
          class="register-form"
          ref="formRef"
        >
          <!-- 患者字段 -->
          <template v-if="selectedRole === 'patient'">
            <el-form-item label="用户名" required>
              <el-input 
                v-model="basicForm.username" 
                placeholder="请输入用户名" 
                size="large"
              />
            </el-form-item>
            
            <el-form-item label="手机号" required>
              <el-input 
                v-model="basicForm.phone" 
                placeholder="请输入手机号" 
                size="large"
              />
            </el-form-item>
          </template>
          
          <!-- 医生字段 -->
          <template v-else-if="selectedRole === 'doctor'">
            <el-form-item label="用户名" required>
              <el-input 
                v-model="basicForm.username" 
                placeholder="请输入用户名" 
                size="large"
              />
            </el-form-item>
            
            <el-form-item label="手机号" required>
              <el-input 
                v-model="basicForm.phone" 
                placeholder="请输入手机号" 
                size="large"
              />
            </el-form-item>
            
            <el-form-item label="医院" required>
              <el-input 
                v-model="basicForm.hospital" 
                placeholder="请输入所在医院" 
                size="large"
              />
            </el-form-item>
            
            <el-form-item label="科室" required>
              <el-input 
                v-model="basicForm.department" 
                placeholder="请输入所在科室" 
                size="large"
              />
            </el-form-item>
            
            <el-form-item label="职称" required>
              <el-input 
                v-model="basicForm.title" 
                placeholder="请输入职称" 
                size="large"
              />
            </el-form-item>
          </template>
          
          <!-- 管理员字段 -->
          <template v-else-if="selectedRole === 'admin'">
            <el-form-item label="用户名" required>
              <el-input 
                v-model="basicForm.username" 
                placeholder="请输入用户名" 
                size="large"
              />
            </el-form-item>
            
            <el-form-item label="医院" required>
              <el-input 
                v-model="basicForm.hospital" 
                placeholder="请输入所属医院" 
                size="large"
              />
            </el-form-item>
          </template>
          
          <!-- 公共密码字段 -->
          <el-form-item label="密码" required>
            <el-input 
              v-model="basicForm.password" 
              type="password" 
              placeholder="请输入密码"
              show-password
              size="large"
            />
          </el-form-item>
          
          <el-form-item label="确认密码" required>
            <el-input 
              v-model="basicForm.confirmPassword" 
              type="password" 
              placeholder="请再次输入密码"
              show-password
              size="large"
            />
          </el-form-item>
          
          <el-form-item class="form-actions">
            <el-button @click="prevStep" size="large">上一步</el-button>
            <el-button type="primary" @click="nextStep" size="large">下一步</el-button>
          </el-form-item>
        </el-form>
        
        <div class="link-text">
          <span>已有账号？</span>
          <el-link type="primary" @click="returnToLogin">返回登录</el-link>
        </div>
      </div>
      
      <!-- 第三步：钱包连接 -->
      <div v-if="activeStep === 3" class="step-content">
        <div class="wallet-registration">
          <h3 class="wallet-title">连接钱包完成注册</h3>
          
          <div class="wallet-connect-card">
            <div class="wallet-icon">
              
            </div>
            
            <div class="wallet-info">
              <h4>MetaMask 钱包</h4>
              <p>连接您的MetaMask钱包以完成区块链账户注册</p>
            </div>
            
            <el-button 
              class="connect-button"
              :type="walletConnected ? 'success' : 'primary'"
              @click="connectWallet"
              :loading="walletConnecting"
              :disabled="walletConnected"
              size="large"
            >
              <span v-if="walletConnected">已连接: {{ truncatedWalletAddress }}</span>
              <span v-else>连接 MetaMask</span>
            </el-button>
          </div>
          
          <div class="wallet-instructions">
            <h4>使用说明:</h4>
            <ol>
              <li>确保您已安装MetaMask浏览器扩展</li>
              <li>点击"连接MetaMask"按钮</li>
              <li>在弹出的MetaMask窗口中授权连接</li>
              <li>连接成功后点击"完成注册"按钮</li>
            </ol>
          </div>
          
          <div class="form-actions">
            <el-button @click="prevStep" size="large">上一步</el-button>
            <el-button 
              type="success" 
              @click="submitRegistration"
              :disabled="!walletConnected"
              :loading="registering"
              size="large"
            >
              完成注册
            </el-button>
          </div>
        </div>
        
        <div class="link-text">
          <span>已有账号？</span>
          <el-link type="primary" @click="returnToLogin">返回登录</el-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/store'
import { User, FirstAidKit, Setting } from '@element-plus/icons-vue'
import Web3 from 'web3'

const authStore = useAuthStore()
const router = useRouter()
const activeStep = ref(1)
const selectedRole = ref('patient')

// 钱包相关状态
const web3 = ref(null)
const walletAddress = ref('')
const walletConnected = ref(false)
const walletConnecting = ref(false)
const registering = ref(false)

// 基本信息表单
const basicForm = ref({
  username: '',
  phone: '',
  password: '',
  confirmPassword: '',
  // 医生特有
  hospital: '',
  department: '',
  title: '',
})

// 截断显示的钱包地址
const truncatedWalletAddress = computed(() => {
  if (!walletAddress.value) return ''
  return `${walletAddress.value.substring(0, 6)}...${walletAddress.value.substring(38)}`
})

// 检查是否安装MetaMask
const checkMetaMaskInstalled = () => {
  return typeof window.ethereum !== 'undefined'
}

// 初始化Web3
const initWeb3 = async () => {
  if (!checkMetaMaskInstalled()) {
    ElMessage.error('请安装MetaMask钱包扩展')
    return false
  }

  try {
    // 请求账户访问权限
    const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' })
    
    // 创建Web3实例
    web3.value = new Web3(window.ethereum)
    
    if (accounts.length > 0) {
      walletAddress.value = accounts[0]
      walletConnected.value = true
      
      // 监听账户变化
      window.ethereum.on('accountsChanged', handleAccountsChanged)
      
      return true
    }
  } catch (error) {
    console.error('连接钱包失败:', error)
    ElMessage.error('连接钱包失败: ' + (error.message || '未知错误'))
    return false
  }
}

// 处理账户变化
const handleAccountsChanged = (accounts) => {
  if (accounts.length === 0) {
    // 用户已断开连接
    disconnectWallet()
  } else {
    // 账户已更改
    walletAddress.value = accounts[0]
    ElMessage.info('检测到钱包账户变更')
  }
}

// 连接钱包
const connectWallet = async () => {
  walletConnecting.value = true
  
  try {
    const success = await initWeb3()
    if (success) {
      ElMessage.success('钱包连接成功')
    }
  } catch (error) {
    console.error('连接钱包错误:', error)
    ElMessage.error('连接钱包时出错')
  } finally {
    walletConnecting.value = false
  }
}

// 断开钱包连接
const disconnectWallet = () => {
  walletAddress.value = ''
  walletConnected.value = false
  web3.value = null
  
  // 移除事件监听
  if (window.ethereum) {
    window.ethereum.removeListener('accountsChanged', handleAccountsChanged)
  }
}

// 选择角色
const selectRole = (role) => {
  selectedRole.value = role
}

// 下一步
const nextStep = () => {
  if (activeStep.value === 1 && !selectedRole.value) {
    ElMessage.error('请选择角色')
    return
  }
  
  if (activeStep.value === 2) {
    // 表单验证逻辑
    let valid = true
    
    // 通用验证
    if (!basicForm.value.username) {
      ElMessage.error('请输入用户名')
      return
    }
    
    if (!basicForm.value.password) {
      ElMessage.error('请输入密码')
      return
    }
    
    if (!basicForm.value.confirmPassword) {
      ElMessage.error('请确认密码')
      return
    }
    
    if (basicForm.value.password !== basicForm.value.confirmPassword) {
      ElMessage.error('两次输入的密码不一致')
      return
    }
    
    // 角色特有验证
    if (selectedRole.value === 'patient') {
      if (!basicForm.value.phone) {
        ElMessage.error('请输入手机号')
        return
      }
    }
    
    if (selectedRole.value === 'doctor') {
      if (!basicForm.value.phone) {
        ElMessage.error('请输入手机号')
        return
      }
      
      if (!basicForm.value.hospital) {
        ElMessage.error('请输入医院')
        return
      }
      
      if (!basicForm.value.department) {
        ElMessage.error('请输入科室')
        return
      }
      
      if (!basicForm.value.title) {
        ElMessage.error('请输入职称')
        return
      }
    }
    
    if (selectedRole.value === 'admin') {
      if (!basicForm.value.hospital) {
        ElMessage.error('请输入医院')
        return
      }
    }
    
    // 检查用户名是否已注册
    if (authStore.registeredUsers.some(user => user.username === basicForm.value.username)) {
      ElMessage.error('该用户名已被注册')
      return
    }
  }
  
  activeStep.value += 1
}

// 上一步
const prevStep = () => {
  if (activeStep.value > 1) {
    activeStep.value -= 1
  }
}

// 返回登录
const returnToLogin = () => {
  router.push('/login')
}

// 提交注册
const submitRegistration = async () => {
  if (!walletConnected.value) {
    ElMessage.error('请先连接钱包')
    return
  }

  registering.value = true
  
  try {
    // 调用注册API
    const success = await authStore.register({
      ...basicForm.value,
      role: selectedRole.value,
      walletAddress: walletAddress.value
    })
    
    if (success) {
      ElMessage.success('注册成功！即将跳转到登录页面')
      
      // 模拟延迟后跳转
      setTimeout(() => {
        router.push('/login')
      }, 2000)
    } else {
      ElMessage.error('注册失败，请稍后再试')
    }
  } catch (error) {
    console.error('注册错误:', error)
    ElMessage.error('注册失败: ' + (error.message || '未知错误'))
  } finally {
    registering.value = false
  }
}

</script>

<style scoped>
.auth-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #1e5799 0%, #207cca 100%);
}

.auth-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.register-title {
  text-align: center;
  margin-bottom: 20px;
  color: #1e5799;
  font-size: 24px;
}

.step-content {
  margin-top: 30px;
}

.register-form {
  max-width: 600px;
  margin: 0 auto 20px;
}

.role-selection {
  text-align: center;
  padding: 10px;
}

.role-selection h3 {
  margin-bottom: 20px;
  color: #333;
  font-size: 18px;
}

.role-cards {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30px;
}

.role-card {
  width: 200px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 8px;
}

.role-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.role-card.selected {
  border: 2px solid #1e5799;
  background-color: #f5f7fa;
}

.role-icon {
  width: 60px;
  height: 60px;
  margin: 0 auto 15px;
  background: #e6f7ff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.role-icon .el-icon {
  font-size: 28px;
  color: #1e5799;
}

.role-card h4 {
  margin-bottom: 10px;
  color: #333;
  font-size: 16px;
}

.role-card p {
  font-size: 13px;
  color: #666;
  line-height: 1.5;
}

.action-buttons {
  margin: 20px 0;
}

.next-btn {
  width: 150px;
  height: 40px;
  background-color: #1e5799;
  border: none;
  font-size: 16px;
}

.form-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.link-text {
  text-align: center;
  font-size: 14px;
  color: #606266;
  margin-top: 10px;
}

.link-text .el-link {
  margin-left: 5px;
  color: #1e5799;
  font-weight: 500;
}

/* 钱包注册部分样式 */
.wallet-registration {
  max-width: 600px;
  margin: 0 auto;
}

.wallet-title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.wallet-connect-card {
  display: flex;
  align-items: center;
  padding: 20px;
  margin-bottom: 30px;
  background: #f9fafc;
  border-radius: 8px;
  border: 1px solid #e6e8f0;
}

.wallet-icon {
  width: 60px;
  height: 60px;
  margin-right: 20px;
}

.wallet-icon img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.wallet-info {
  flex: 1;
}

.wallet-info h4 {
  margin: 0 0 5px 0;
  font-size: 18px;
  color: #333;
}

.wallet-info p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.connect-button {
  width: 200px;
}

.wallet-instructions {
  padding: 20px;
  margin-bottom: 30px;
  background: #f5f7fa;
  border-radius: 8px;
}

.wallet-instructions h4 {
  margin-top: 0;
  color: #333;
}

.wallet-instructions ol {
  padding-left: 20px;
  margin-bottom: 0;
}

.wallet-instructions li {
  margin-bottom: 8px;
  color: #666;
}

.wallet-instructions li:last-child {
  margin-bottom: 0;
}
</style>